from flask import Flask, request, jsonify, send_file
import os
from typing import Optional

from ai_translator.translator import PDFTranslator

app = Flask(__name__)

#翻译器
translator: Optional[PDFTranslator] = None

# 上传文件存储的目录
upload_folder = './uploads'
app.config['UPLOAD_FOLDER'] = upload_folder
# 下载目录
download_folder = './downloads'
app.config['DOWNLOAD_FOLDER'] = download_folder
# 确保上传下载目录存在
if not os.path.exists(upload_folder):
    os.makedirs(upload_folder)
if not os.path.exists(download_folder):
    os.makedirs(download_folder)

# http://localhost:5000/pdf_translate/<file_format>/<target_lang>
# file_format： 文件格式 可选值[pdf, markdown]
# target_lang:  目标语言 可选值[中文, 法语, 德语, 日语]
@app.route('/pdf_translate/<file_format>/<target_lang>', methods=['POST'])
def pdf_translate(file_format, target_lang):
    # 检查是否有文件上传
    if 'file' not in request.files:
        return jsonify({"error": "No file part"}), 400

    file = request.files['file']

    # 如果用户没有选择文件
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400
    if file:
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
        file.save(file_path)  # 保存文件

        translator.translate_pdf(file_path, file_format, target_lang, output_file_path=download_folder)

        download_filename = file.filename.replace('.pdf', '') + '_translated'
        if file_format == 'pdf':
            download_filename = download_filename + '.pdf'
        elif file_format == 'markdown':
            download_filename = download_filename + '.md'

        return jsonify({"message": "File uploaded successfully", "filename": download_filename}), 200


@app.route('/get_result/<filename>', methods=['GET'])
def get_result(filename):
    file_path = os.path.join(app.config['DOWNLOAD_FOLDER'], filename)

    # 检查文件是否存在
    if not os.path.exists(file_path):
        return jsonify({"error": "File not found"}), 404
    print(file_path)
    return send_file(os.path.abspath(file_path), as_attachment=True, download_name=filename)

# 启动函数
def run(translator_:PDFTranslator):
    global translator
    translator = translator_
    app.run(debug=True)
